<template>
  <!-- 卡片区域 -->
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>卡片基本资料名称</span>
    </div>
    <!-- 表单 -->
    <el-form label-width="80px" :model="userinfo" :rules="userinfoRules" ref="userinfoRef">
      <el-form-item label="登录名称">
        <el-input v-model="userinfo.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="userinfo.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="userinfo.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="update">提交按钮</el-button>
        <el-button @click="rest">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { updateUserAPI } from '@/api/user.js'
export default {
  name: 'UserInfo',
  data() {
    return {
      // 用户的信息对象
      userinfo: {
        ...this.$store.state.user.user
      },
      // 校验规则
      userinfoRules: {
        // 用户昵称规则
        nickname: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { pattern: /^\S{1,10}$/, message: '非空字符串、长度 1-10', trigger: 'blur' }
        ],
        // 用户邮箱规则
        email: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  methods: {
    rest() {
      this.$refs.userinfoRef.resetFields()
      this.userinfo = Object.assign({}, this.$store.state.user.user)
    },
    update() {
      this.$refs.userinfoRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await updateUserAPI(this.userinfo)
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.$store.dispatch('user/initUser')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 500px;
}
</style>
